#include "Model.h"

Vertex::Vertex(Vector3 p, Vector3 n, Vector3 c, Vector2 t)
{
	Position = p;
	Normal = n;
	Color = c;
	Texcoord = t;
}
Vertex::Vertex()
{
}
Model::Model(const char* fileName)
{
	std::ifstream file(fileName);

	LoadOBJ(file);

	file.close();
}
Model::~Model()
{
}
void Model::LoadOBJ(std::ifstream& file)
{
	std::vector<Vector3> Positions;
	std::vector<Vector3> Normals;
	std::vector<Vector2> Texcoords;

	std::vector<Vertex> Vertices;

	while (!file.eof())
	{
		char line[1024];
		file.getline(line, 1024, '\n');

		if (line[0] == 'v' && line[1] == 'n')
		{
			Vector3 v;
			sscanf(line, "vn %f %f %f", &v.x, &v.y, &v.z);
			Normals.push_back(v);
		}
		else if (line[0] == 'v' && line[1] == 't')
		{
			Vector2 v;
			sscanf(line, "vt %f %f", &v.x, &v.y);
			Texcoords.push_back(v);
		}
		else if (line[0] == 'v' && line[1] == ' ')
		{
			Vector3 v;
			sscanf(line, "v %f %f %f", &v.x, &v.y, &v.z);
			Positions.push_back(v);
		}
		else if (line[0] == 'f')
		{
			int p[3], t[3], n[3];
			sscanf(line, "f %d/%d/%d %d/%d/%d %d/%d/%d", 
				&p[0], &t[0], &n[0], 
				&p[1], &t[1], &n[1], 
				&p[2], &t[2], &n[2]);

			for (int i=0; i<3; ++i)
			{
				Vertices.push_back(Vertex(	Positions[p[i]-1], 
											Normals[n[i]-1],
											Vector3(1, 1, 1),
											Texcoords[t[i]-1]));
			}
		}
	}

	nVertices = Vertices.size();
	pVertices = new Vertex[nVertices];

	memcpy(pVertices, &Vertices[0], sizeof(Vertex) * nVertices);
	printf("model loaded!!\n");
}
void Model::Load3DS(std::ifstream& file)
{
}
void Model::Draw(ShaderInfo shi)
{
	glVertexAttribPointer(shi.position, 3, GL_FLOAT, GL_FALSE,  sizeof(Vertex), pVertices);
	glVertexAttribPointer(shi.normal,   3, GL_FLOAT, GL_FALSE,  sizeof(Vertex), pVertices + sizeof(Vector3));
	glVertexAttribPointer(shi.color, 	3, GL_FLOAT, GL_FALSE,  sizeof(Vertex), pVertices + sizeof(Vector3) * 2);

	glEnableVertexAttribArray(shi.position);
	glEnableVertexAttribArray(shi.normal);
	glEnableVertexAttribArray(shi.color);
	
	glDrawArrays(GL_TRIANGLES, 0, nVertices);

	glDisableVertexAttribArray(shi.position);
	glDisableVertexAttribArray(shi.normal);
	glDisableVertexAttribArray(shi.color);
}
